<template>
  <div class="goods">
    <div class="goods-content">
      <div class="title">全部规格</div>
      <div class="operation-box">
        <el-button type="success" :icon="Plus" @click="add_goods"
          >添加规格</el-button
        >

        <!-- <el-button type="success" :icon="Plus" @click="add_goods_all"
          >批量添加</el-button
        >   -->
        <el-button type="primary" :icon="Refresh" @click="table_reload"
          >刷新</el-button
        >
        <el-button
          type="danger"
          v-if="table_data_origin && table_data_origin.length > 0"
          :icon="Download"
          @click="export_excel(table_data_origin, '全部商品')"
          >导出数据</el-button
        >

        <el-input
          v-model="search_item_number"
          class="w-50 m-2"
          size="default"
          style="width: 180px; margin: 0 10px 0 30px"
          clearable
          :prefix-icon="Search"
          @input="search_filter"
          placeholder="输入货号搜索"
        />

        <el-button type="default" @click="search_reset">重置</el-button>
      </div>

      <section class="table-data-box" v-if="table_data">
        <el-table
          :data="table_data"
          v-loading="table_loading"
          table-layout="fixed"
          style="width: 95%; margin: 0 auto"
        >
          <!-- <el-table-column label="生产日期" prop="date" /> -->
          <el-table-column label="商品名称" prop="goods_name" width="550" />
          <el-table-column label="分类" prop="kind" width="100"/>
          <el-table-column label="条码" prop="bar_code" width="160"/>
          <el-table-column label="货号" prop="item_number" width="120"/>
          <el-table-column label="颜色" prop="color" width="80"/>
          <el-table-column label="尺码" prop="size" width="80"/>
          <el-table-column label="库存量" width="100">
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <span :style="{ color: scope.row.stock < 20 ? 'red' : '' }">{{
                  scope.row.stock
                }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="进货价" width="100">
            <template #default="scope">
              <div style="display: flex; align-items: center">
                {{ scope.row.cost }}元
              </div>
            </template>
          </el-table-column>
          <el-table-column label="销售价" >
            <template #default="scope">
              <div style="display: flex; align-items: center">
                {{ scope.row.price }}元
              </div>
            </template>
          </el-table-column>

          <el-table-column fixed="right" label="操作" width="120">
            <template #default="scope">
              <el-button
                link
                type="primary"
                size="large"
                @click="before_handle_edit(scope.$index, scope.row)"
                >编辑</el-button
              >

              <el-popconfirm
                confirm-button-text="是"
                cancel-button-text="否"
                :icon="InfoFilled"
                icon-color="#626AEF"
                title="是否确定删除"
                @confirm="handle_delete(scope.$index, scope.row)"
                @cancel="cancelEvent"
              >
                <template #reference>
                  <el-button link size="large" type="danger" style="color: red"
                    >删除</el-button
                  >
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </section>

      <!-- 编辑&新增 角色信息窗口 -->
      <el-drawer v-model="show_info" :direction="direction">
        <template #header>
          <h4 style="text-align: left">
            {{
              show_info == "edit"
                ? "编辑规格"
                : show_info == "new"
                ? "添加规格"
                : ""
            }}
          </h4>
        </template>
        <template #default>
          <div>
            <el-form
              label-position="left"
              label-width="100px"
              v-if="show_info == 'edit'"
              :model="edit_info"
              style="max-width: 460px"
            >
              <el-form-item label="商品名称">
                <el-input
                  placeholder="请输入商品名称"
                  clearable
                  v-model="edit_info.goods_name"
                />
              </el-form-item>

              <el-form-item label="分类">
                <el-input
                  placeholder="请输入分类"
                  clearable
                  v-model="edit_info.kind"
                />
              </el-form-item>

              <el-form-item label="条码">
                <el-input
                  placeholder="请输入条码"
                  clearable
                  v-model="edit_info.bar_code"
                />
              </el-form-item>

              <el-form-item label="货号">
                <el-input
                  placeholder="请输入货号"
                  clearable
                  v-model="edit_info.item_number"
                />
              </el-form-item>

              <el-form-item label="颜色">
                <el-input
                  placeholder="请输入颜色"
                  clearable
                  v-model="edit_info.color"
                />
              </el-form-item>
              <el-form-item label="尺寸">
                <el-input
                  placeholder="请输入尺寸"
                  clearable
                  v-model="edit_info.size"
                />
              </el-form-item>

              <el-form-item label="库存量">
                <el-input-number v-model="edit_info.stock" step-strictly />
              </el-form-item>
              <el-form-item label="进货价">
                <el-input-number v-model="edit_info.cost" />
              </el-form-item>
              <el-form-item label="销售价">
                <el-input-number v-model="edit_info.price" />
              </el-form-item>

            </el-form>

            <el-form
              label-position="left"
              label-width="100px"
              v-if="show_info == 'new'"
              :model="new_info"
              style="max-width: 460px"
            >
              <el-form-item label="商品名称">
                <el-input
                  placeholder="请输入商品名称"
                  clearable
                  v-model="new_info.goods_name"
                />
              </el-form-item>

              <el-form-item label="分类">
                <el-input
                  placeholder="请输入分类"
                  clearable
                  v-model="new_info.kind"
                />
              </el-form-item>

              <el-form-item label="条码">
                <el-input
                  placeholder="请输入条码"
                  clearable
                  v-model="new_info.bar_code"
                />
              </el-form-item>

              <el-form-item label="货号">
                <el-input
                  placeholder="请输入货号"
                  clearable
                  v-model="new_info.item_number"
                />
              </el-form-item>

              <el-form-item label="颜色">
                <el-input
                  placeholder="请输入颜色"
                  clearable
                  v-model="new_info.color"
                />
              </el-form-item>
              <el-form-item label="尺寸">
                <el-input
                  placeholder="请输入尺寸"
                  clearable
                  v-model="new_info.size"
                />
              </el-form-item>

              <el-form-item label="库存量">
                <el-input-number v-model="new_info.stock" step-strictly />
              </el-form-item>
              <el-form-item label="进货价">
                <el-input-number v-model="new_info.cost" />
              </el-form-item>
              <el-form-item label="销售价">
                <el-input-number v-model="new_info.price" />
              </el-form-item>
            </el-form>
          </div>
        </template>
        <template #footer>
          <div style="flex: auto">
            <el-button @click="show_info = false">取消</el-button>
            <el-button
              type="primary"
              @click="handle_commit"
              v-loading.fullscreen.lock="global_loading"
              >提交</el-button
            >
          </div>
        </template>
      </el-drawer>
    </div>

    <el-pagination
      v-model:currentPage="current_page" 
      v-model:page-size="page_size"
      :page-sizes="[10,15, 20, 50]"
      :small="small"
      :disabled="disabled"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      style="
        display: flex;
        justify-content: flex-start;
        margin-top: 20px;
        margin-left: 2.5%;
      "
      :total="pagination_total"
      @size-change="handleSizeChange" 
      @current-change="pageChange"
    />

  </div>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import {
  Refresh,
  Download,
  Search,
  Timer,
  Plus,
  Picture as IconPicture,
} from "@element-plus/icons-vue";
import { export_excel } from "../../../common/utils";
import { ElMessage, UploadProps } from "element-plus";
import {
  addGoodsItem,
  addGoodsItemAll,
  getGoodsItems,
  updateGoodsItem,
  delGoodsItem,
  addGoodsAll
} from "../../ajaxServices/goods";

import jsonData from "./target_Sheet1.json"
import GoodsData from "./goods_Sheet1.json"

const parentBorder = ref(false);
const childBorder = ref(false);

const table_data_origin = ref([]);

// const table_data = ref<Goods>(table_data_origin);
const table_data = ref([]);

const table_loading = ref(false);
const search_item_number = ref("");
const current_page = ref(1); // 当前页码
const page_size = ref(10); // 每页条数
const pagination_total = ref(1); // 页码总条数

const props = { expandTrigger: 'hover'} // 所属分类鼠标划入自动展示第二级联内容
const table_svg = `
        <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
      `;

const search_filter = () => {
  if (search_item_number.value == "") {
    table_data.value = table_data_origin.value
    return;
  }

  if (search_item_number.value != "") {
    table_data.value = table_data_origin.value ? table_data_origin.value.filter((data: any) =>
      data.item_number
        .toLowerCase()
        .includes(search_item_number.value.toLowerCase())
    ) : []
  }
};

// 重置搜索框
const search_reset = () => {
  search_item_number.value = "";
  table_data.value = table_data_origin.value || [];
};

// 刷新表格数据
const table_reload = () => {
  table_loading.value = true;
  let reqData = {
    page_size: page_size.value,
    page_count: current_page.value,
  };

  getGoodsItems(reqData)
    .then((res: any) => {

      table_loading.value = false;
      table_data_origin.value = res.data || [];
      table_data.value = res.data || [];
      pagination_total.value = res.total || 1;
    })
    .catch(() => {
      table_loading.value = false;
    });
};
table_reload();

// 分页器相关
const handleSizeChange = (val:any) => {
  page_size.value = val
  table_reload();
}


const pageChange = (val:any) => {
  current_page.value = val
  table_reload();
}

/*
    删除商品相关
*/
const handle_delete = (index: number, row: any) => {
  if (!row.item_number || row.item_number == "") {
    ElMessage({ message: "货号不能为空", type: "warning" });
    return;
  }
  table_loading.value = true;
  delGoodsItem({ item_number: row.item_number || "" })
    .then((res: any) => {
      ElMessage({
        message: "删除成功",
        type: "success",
      });
      // 重新加载表单数据
      table_reload();
    })
    .catch(() => {
      table_loading.value = false;
    });
};

/*
    新增&编辑商品相关
*/
const show_info = ref(false);
const edit_info = ref(null); // 编辑商品表单
const global_loading = ref(false); // 表单提交按钮loading状态
const new_info = ref({
  goods_name: "", // 商品名称
  kind: "", // 分类
  bar_code: "", // 条码
  item_number: "", // 货号
  color: "", // 颜色
  size: "", // 尺寸
  stock: 0, // 库存量
  cost: 0, // 进货价
  price: 0, // 销售价
});
const before_handle_edit = (index: number, row: any) => {
  edit_info.value = row;
  show_info.value = "edit";
  console.log(index, row);
};

const imageUrl = ref("");

const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response: any,
  uploadFile: any
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!);
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile: any) => {
  //   if (rawFile.type !== "image/jpeg") {
  //     ElMessage.error("Avatar picture must be JPG format!");
  //     return false;
  //   } else if (rawFile.size / 1024 / 1024 > 2) {
  //     ElMessage.error("Avatar picture size can not exceed 2MB!");
  //     return false;
  //   }
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("图片大小不得超过2MB");
    return false;
  }
  return true;
};

const add_goods = () => {
  // 添加商品重置商品数据
  new_info.value = {
    goods_name: "",
    kind: "",
    bar_code: "",
    item_number: "",
    color: "",
    size: "",
    stock: 0,
    cost: 0,
    price: 0 
  };
  show_info.value = "new";
};

// 批量将json数据插入MySQL表内 11111111111
const add_goods_all = () => {
  let targetArr = [];
  console.log("111111111111")
  console.log(GoodsData)
  for(let item of GoodsData) {
    targetArr.push({
      goods_id: 0, // 商品id
      goods_name: item["商品名称"],
      stock: Number(item["库存"]),
      cost: Number(item["进货价"]),
      price: Number(item["销售价"]),
      origin_price: Number(item["销售价"]) + 200,
      color: item["颜色"],
      size: "",
      cover: "",
      hot: 0,
      degree_of_praise: "",
      shelf_flag: 0,
      quantity_sold: 0,
      monthly_sale: 0,
      menu_first_id: "",
      menu_second_id: "",
      suggest: 0,
      item_number: item["货号"],
      kind: item["商品分类"],
      supplier: "",
    })
  }

  addGoodsAll({
    data: targetArr.slice(200,271)
  })
  // for(let item of jsonData) {
  //     targetArr.push({
  //       goods_name: item["名称（必填）"],
  //       kind: item["分类（必填）"],
  //       bar_code: item["条码（不填系统默认生成）"],
  //       item_number: item["货号（必填）"],
  //       color: item["颜色（必填）"],
  //       size: item["尺码（必填）"],
  //       stock: Number(item["库存量（必填）"]),
  //       cost: Number(item["进货价（必填）"]),
  //       price: Number(item["销售价（必填）"])
  //     });
  // }
  // addGoodsItemAll({
  //   data: targetArr.slice(3600,3941)
  // })

}

const handle_commit = () => {
  // 编辑修改
  if (show_info.value == "edit") {
    if (!edit_info.value.goods_name || edit_info.value.goods_name == "") {
      ElMessage({ message: "商品名称不能为空", type: "warning" });
      return;
    }

    if (!edit_info.value.kind || edit_info.value.kind == "") {
      ElMessage({ message: "分类不能为空", type: "warning" });
      return;
    }

    if (!edit_info.value.bar_code || edit_info.value.bar_code == "") {
      ElMessage({ message: "条码不能为空", type: "warning" });
      return;
    }

    if (!edit_info.value.item_number || edit_info.value.item_number == "") {
      ElMessage({ message: "货号不能为空", type: "warning" });
      return;
    }

    if (!edit_info.value.color || edit_info.value.color == "") {
      ElMessage({ message: "颜色不能为空", type: "warning" });
      return;
    }

    if (!edit_info.value.size || edit_info.value.size == "") {
      ElMessage({ message: "尺寸不能为空", type: "warning" });
      return;
    }


    let reqData = {
      goods_name: edit_info.value.goods_name || "",
      kind: edit_info.value.kind || "",
      bar_code: edit_info.value.bar_code || "",
      item_number: edit_info.value.item_number || "",
      color: edit_info.value.color || "",
      size: edit_info.value.size || "",
      stock: edit_info.value.stock || 0,
      cost: edit_info.value.cost || 0,
      price: edit_info.value.price || 0,

    };
    global_loading.value = true;
    updateGoodsItem(reqData)
      .then((res: any) => {
        global_loading.value = false;
        show_info.value = false;
        ElMessage({
          message: "修改成功",
          type: "success",
        });
        // 重新加载表单数据
        table_reload();
      })
      .catch(() => {
        global_loading.value = false;
      });
    return;
  }

  // 新增
  if (show_info.value == "new") {
    if (!new_info.value.goods_name || new_info.value.goods_name == "") {
      ElMessage({ message: "商品名称不能为空", type: "warning" });
      return;
    }
    if (!new_info.value.kind || new_info.value.kind == "") {
      ElMessage({ message: "分类不能为空", type: "warning" });
      return;
    }
    if (!new_info.value.bar_code || new_info.value.bar_code == "") {
      ElMessage({ message: "条码不能为空", type: "warning" });
      return;
    }
    if (!new_info.value.item_number || new_info.value.item_number == "") {
      ElMessage({ message: "货号不能为空", type: "warning" });
      return;
    }
    if (!new_info.value.color || new_info.value.color == "") {
      ElMessage({ message: "颜色不能为空", type: "warning" });
      return;
    }
    if (!new_info.value.size || new_info.value.size == "") {
      ElMessage({ message: "尺寸不能为空", type: "warning" });
      return;
    }

    let reqData = {
      goods_name: new_info.value.goods_name || "",
      kind: new_info.value.kind || "",
      bar_code: new_info.value.bar_code || "", 
      item_number: new_info.value.item_number || "", 
      color: new_info.value.color || "", 
      size: new_info.value.size || "", 
      stock: new_info.value.stock || 0, 
      cost: new_info.value.cost || 0, 
      price: new_info.value.price || 0, 

    };
    global_loading.value = true;
    addGoodsItem(reqData)
      .then((res: any) => {
        global_loading.value = false;
        show_info.value = false;
        ElMessage({
          message: "添加成功",
          type: "success",
        });
        // 重新加载表单数据
        table_reload();
      })
      .catch(() => {
        global_loading.value = false;
      });
  }
};
</script>


<style scoped lang="scss">
.goods {
  max-height: calc(100vh - 180px);
  overflow-y: scroll;
  .goods-content {
    width: 95%;
    height: 80%;
    border: 1px solid #eee;
    border-radius: 5px;
    margin: auto;
    box-shadow: 0px 0px 6px rgba(0, 0, 0, 0.12);

    .title {
      width: 100%;
      height: 55px;
      font-size: 18px;
      color: #000;
      text-align: left;
      line-height: 55px;
      text-indent: 20px;
      border-bottom: 1px solid #eee;
    }

    .operation-box {
      width: 100%;
      height: 70px;
      display: flex;
      align-items: center;
      padding-left: 20px;
    }
  }
  .avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .demo-image__error .demonstration {
    display: block;
    color: var(--el-text-color-secondary);
    font-size: 14px;
    margin-bottom: 20px;
  }
  .demo-image__error .el-image {
    max-width: 300px;
    max-height: 200px;
    width: 100%;
  }

  .demo-image__error .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: var(--el-fill-color-light);
    color: var(--el-text-color-secondary);
    font-size: 30px;
  }
  .demo-image__error .image-slot .el-icon {
    font-size: 30px;
  }
}
</style>

<style>
.el-dialog__header,
.el-dialog__body {
  text-align: left;
}
.el-table__cell {
  position: static !important;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.el-drawer__header {
  margin-bottom: 0;
}
</style>






